package com.lbtc.filter;


import com.lbtc.common.Constant;
import com.lbtc.domian.User;
import com.lbtc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;


public class AdminFilter implements Filter {
    @Autowired
    private UserService userService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        User currentUser = (User)session.getAttribute(Constant.LBTC_MALL_USER);
        if(currentUser==null){
//return ApiRestResponse.error(SmoothMallExceptionEnum.NEED_LOGIN);
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse)
                    servletResponse).getWriter();
            out.write("{\n" +
                    " \"status\": 100011,\n" +
                    " \"msg\": \"NEED_LOGIN\",\n" +
                    " \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            return;//出错情况下，直接过滤，过滤器不往下执行
        }
//校验是否是管理员
        boolean adminRole = userService.checkAdminRole(currentUser);
        if(adminRole){
//如果是管理员，放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse)
                    servletResponse).getWriter();
            out.write("{\n" +
                    " \"status\": 10012,\n" +
                    " \"msg\": \"NEED_ADMIN\",\n" +
                    " \"data\": null\n" +
                    "}");
            out.flush();
            out.close(); }
    }
    @Override
    public void destroy() {
    }
}
